<script setup lang="ts">
import { reactive, defineProps, defineEmits, watch, toRaw } from 'vue'
import { getApi, updateApi, createApi } from '/@/api/mes/product'
import { useInModal } from '/@/hooks/useModal'
import { useInsertSucessMessage, useUpdateSucessMessage } from '/@/hooks/useMessage'
import { dataFormatter } from '/@/utils/data'

const props = defineProps(({
  id: String
}))

const emits = defineEmits(['change'])

const modal = useInModal()

const formProps = reactive<FormMakerProps>({
  name: 'productForm',
  model: {
    code: '',
    name: '',
    spec: '',
    unit: 'PCS',
    calcUnit: 'PCS'
  },
  options: [
    { field: "code", label: "产品编码", required: true },
    { field: "name", label: "产品名称", required: true },
    { field: "spec", label: "规格", required: true },
    { field: "unit", label: "单位", required: true },
    { field: "calcUnit", label: "计量单位", required: true },
  ]
})

const tableProps = reactive<YTableProps>({
  height: "auto",
  data: [],
  columns: [
    {
      field: "processId", label: "工序", width: 100, edit: true,
      editComponent: {
        key: 'SelectMaker',
        props: {
          dataSource: 'Process'
        }
      },
      formatter: (v) => dataFormatter(v, 'Process')
    },
    { field: "planWorkingTime", label: "计划工时", width: 100, edit: true },
    { field: "remark", label: "备注", edit: true },
  ],
  editOperas: ['add', 'delete', 'fill', 'copy', 'drag'],
  config: {
    edit: true
  }
});

watch(() => props.id, (id: string) => {
  if (id) {
    modal.loading(true)
    getApi(id)
      .then(res => {
        Object.assign(formProps.model, res.data)
        tableProps.data = res.data.standCrafts
      })
      .finally(() => modal.loading(false))
  }
}, { immediate: true })

const viewLayout: ViewLayoutProps = {
  buttons: [
    {
      title: '确定', type: 'primary', onClick: async () => {
        modal.loading(true)
        try {
          if (props.id) {
            const { succeeded } = await updateApi({
              ...toRaw(formProps.model),
              standCrafts: toRaw(tableProps.data)
            })
            if (succeeded) {
              useUpdateSucessMessage()
            }
          } else {
            const { succeeded } = await createApi({
              ...toRaw(formProps.model),
              standCrafts: toRaw(tableProps.data)
            })
            succeeded && useInsertSucessMessage()
          }
        }
        finally {
          modal.loading(false)
          emits('change')
        }
      }
    },
    { title: '取消', onClick: () => modal.close() },
  ]
}



</script>

<template>
  <ViewLayout v-bind="viewLayout">
    <template #header>
      <FormMaker v-bind="formProps" />
    </template>
    <YTable v-bind="tableProps" ref="tableRef"></YTable>
  </ViewLayout>
</template>